<template>
    <el-dialog
            v-model="dialog.visible"
            :title="dialog.title"
            width="500"
            :before-close="closeDialog"
    >
        <el-form :model="forms" :rules="rules" label-width="auto" style="max-width: 600px" ref="formsRef">
            <el-form-item label="组织名称" prop="name">
                <el-input v-model="forms.name"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="doSubmit(formsRef)">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup type="ts">
import {reactive, ref, defineEmits} from "vue";
import {createCompany} from "@/api/api.company";

const emit = defineEmits(["submit"]);


const formsRef = ref();
const dialog = reactive({
    visible: false,
    title: '创建组织'
})

const forms = reactive({
    name: ''
});

const rules = reactive({
    name: [
        {required: true, message: '请输入组织名称', trigger: 'blur'},
        {max: 20, message: '组织名称不能超过20个字符', trigger: 'blur'}
    ]
})

const openDialog = () => {
    dialog.visible = true;
}

const closeDialog = () => {
    dialog.visible = false;
}

const doSubmit = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            createCompany(forms).then(() => {
                closeDialog();
                emit("submit");
            });
        }
    })
}

const exposed = {
    openDialog
};
defineExpose(exposed);
</script>
